﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity.Infrastructure.Interception;
using System.Data.Common;
using EntityFrameworkETL.Interfaces;

namespace EntityFrameworkETL.Interceptors
{
    public class IdentityInsertCommandCacheInterceptor : IDbCommandInterceptor
    {
        public IdentityInsertCommandCacheInterceptor(Action<DbCommand> cacheCommands)
        {
            CacheCommands = cacheCommands;
        }

        public Action<DbCommand> CacheCommands { get; set; }

        public void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
        {
            //throw new NotImplementedException();
        }

        public void NonQueryExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
        {
            
            if (command.CommandText.StartsWith("INSERT"))
            {
                int iStart = command.CommandText.IndexOf(" ");
                int iEnd = command.CommandText.IndexOf("(");
                string tableName = command.CommandText.Substring(iStart, iEnd - iStart).Trim();
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                sb.AppendLine("SET IDENTITY_INSERT " + tableName + " ON;");
                sb.AppendLine(command.CommandText);
                sb.AppendLine("SET IDENTITY_INSERT " + tableName + " OFF;");
                command.CommandText = sb.ToString();
            }
            CacheCommands(command);
            interceptionContext.SuppressExecution();
            interceptionContext.Result = 1;
        }

        public void ReaderExecuted(System.Data.Common.DbCommand command, DbCommandInterceptionContext<System.Data.Common.DbDataReader> interceptionContext)
        {

        }

        public void ReaderExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext<System.Data.Common.DbDataReader> interceptionContext)
        {
        }

        public void ScalarExecuted(System.Data.Common.DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
        {
        }

        public void ScalarExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
        {
           
        }
    }
}
